﻿using DemoApp2.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DemoApp2.Attribute
{
    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            string authorizationServerAddress = string.Format("{0}{1}?client_id={2}&response_type={3}&redirect_uri={4}",
                    AppConfig.AuthorizationServerBaseAddress, AppConfig.AuthorizePath, AppConfig.ClientId, AppConfig.ResponseType, AppConfig.RedirectUri);

            // Ajax request 
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                // Define a specific status code for Ajax request, so that the ajax request will redirect to login page, this is handled in 'common.js'
                filterContext.Result = new HttpStatusCodeResult(499);
                filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;

                var urlReferrer = filterContext.HttpContext.Request.UrlReferrer;

                if (urlReferrer != null)
                {
                    // Set return URL cookie, the cookie value is used for that after login, redirect this Return URL
                    var cookie = new HttpCookie(AppConfig.ClientReturnUrlCookieName, urlReferrer.ToString());
                    System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
                }

                filterContext.HttpContext.Response.Write(authorizationServerAddress);
            }
            else // Not Ajax request 
            {
                string returnUrl = filterContext.HttpContext.Request.RawUrl;

                // Set return URL cookie, the cookie value is used for that after login, redirect this Return URL
                var cookie = new HttpCookie(AppConfig.ClientReturnUrlCookieName, returnUrl);
                System.Web.HttpContext.Current.Response.Cookies.Add(cookie);

                // Redirect to Authorize action of OAuth server
                filterContext.Result = new RedirectResult(authorizationServerAddress);
            }

            // Before redirect to login page, Remove RefreshedAccessToken Cookie
            HttpCookie refreshedAccessTokenCookie = HttpContext.Current.Request.Cookies[AppConfig.RefreshedAccessTokenCookieName];
            if (refreshedAccessTokenCookie != null)
            {
                refreshedAccessTokenCookie.Expires = DateTime.Now.AddDays(-1);
                HttpContext.Current.Response.Cookies.Add(refreshedAccessTokenCookie);
            }
        }
    }
}